package com.gitee.blogcase.dealyqueuecase.java;

import com.gitee.blogcase.dealyqueuecase.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 延迟队列消费者
 */
@Slf4j
@Component
public class JavaDelayQueueConsumer {
    // 订单超时对象存储的定时队列
    private final DelayQueue<OrderTimeoutDelayed> delayQueue = new DelayQueue<>();
    // 为true的时候启动线程，全局只启动一次
    private final AtomicBoolean start = new AtomicBoolean(false);
    // 任务处理线程
    private Thread thread;
    /**
     * 将需要自动过期的订单放到队列
     * @param orderTimeoutDelayed
     */
    public void monitor(OrderTimeoutDelayed orderTimeoutDelayed){
        delayQueue.add(orderTimeoutDelayed);
    }

    /**
     * 启动过期订单处理
     */
    @PostConstruct
    public void start(){
        if(!start.getAndSet(true)){
            this.thread = new Thread(()->{
                while (true) {
                    try {
                        // 获取已超时的订单
                        OrderTimeoutDelayed take = delayQueue.take();
                        if(take != null){
                            log.info("JUC延迟队列订单号:[{}]已超时当前时间为:[{}]",take.getOrderId(), DateUtil.getCuurentDateStr());
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            this.thread.start();
            log.info("已启动JUC延迟队列消费!");
        }
    }
}
